<!--TODO: Add explanation of the benefits of the rewards program-->

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
        <head><p>
                <style>
                        .error {color: #FF0000;}
                </style>
                <title>New User</title>
				<link type="text/css" rel="stylesheet" href="../stylesheet.css">
        </head>
        <body>
            <h1 class="title">Sandwiches Elliphino's</h1>
			<div>
                <form method="" action="">
                    <input value ="Ayuda" type="submit" >
                </form>    
			</div>
                <div class="form">
        <?php
//initialize all variables to be empty strings
$first = $last = $email = $password = $dob = $address = $phone = $confPassword
  = '';
$firstErr = $lastErr = $emailErr = $passwordErr = $dobErr = $phoneErr =
  $addressErr = '';
$arrCheck = 0;
/*
This code block is accessed whenever a form has been submitted.
It checks that required fields are complete and also checks the format with preg_match.
Special characters are removed using the clean_field function.
 */
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
  if (empty($_POST["first"]))
  {
    $firstErr = "Por favor ingresa tu nombre";
  }
  else
  {
    $first = clean_field($_POST["first"]);
    if (!preg_match("/^[a-zA-Z ]*$/", $first))
    {
      $firstErr = "Nombres solo pueden incluir letras y espacios.";
    }
  }

  if (empty($_POST["last"]))
  {
    $lastErr = "Por favor ingrasa tu apellido";
  }
  else
  {
    $last = clean_field($_POST["last"]);
    if (!preg_match("/^[a-zA-Z ]*$/", $last))
    {
      $lastErr = "Nombres solo pueden incluir letras y espacios.";
    }
  }

  if (empty($_POST["dob"]))
  {
    $dobErr = "Por favor ingresa tu fecha de nacimiento";
  }
  else
  {
    $dob = clean_field($_POST["dob"]);
    if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $dob))
    {
      $dobErr = "Formato incorrecto! Ejemplo: 2014-04-25";
    }
  }

  if (empty($_POST["email"]))
  {
    $emailErr = "Por favor ingresa tu e-mail";
  }
  else
  {
    $email = clean_field($_POST["email"]);
    if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
    {
      $emailErr = "Formato incorrecto! Ejemplo: example@email.com";
    }
  }

  if (empty($_POST["password"]))
  {
    $passwordErr = "Por favor ingresa tu contrese&ntildea";
  }
  else
  {

    $password = clean_field($_POST["password"]);
    $confPassword = clean_field($_POST["confPassword"]);
    if (!preg_match("/^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[a-zA-Z]).{6,}$/",
      $password))
    {
      $passwordErr =
        "Formato incorrecto! La contrase&ntildea debe tener por lo menos 6 caracteres de los cuales uno debe ser una letra y uno debe ser un numero.";
    }
    else if ($password != $confPassword)
    {
      $passwordErr = "Las contrase&ntildeas no coinciden";
    }
    else
    {

        //Generate a hashed password using a randomly generated salt. Store that salt in the database.
      $salt = openssl_random_pseudo_bytes(8);
      $salt = bin2hex($salt);
      $hashed_password = hash("sha256", $password.$salt);
    }

  }

  if (!empty($_POST["phone"]))
  {
    $phone = clean_field($_POST["phone"]);
    if (!preg_match("/^\d{3}-\d{3}-\d{4}$/", $phone))
    {
      $phoneErr = "Formato incorrecto! Ejemplo: 123-456-7890";
    }
  }

  if (!empty($_POST["address"]))
  {
    $address = clean_field($_POST["address"]);
    if (!preg_match("/^[0-9a-zA-Z ]*$/", $address))
    {
      $addressErr =
        "Las direcciones solo pueden  tener letras, numeros y espacios.";
    }
  }

  $errArray = array($firstErr, $lastErr, $emailErr, $passwordErr, $dobErr,
    $phoneErr, $addressErr);

  //Checking to see if there are any errors in the form submission.
  foreach($errArray as $key => $value)
  {
    if (!empty($value))
      $arrCheck = 1;
  }

  if ($arrCheck == 0)
  {
    $username = 'root';
    $pw = 'password';

    //Connect to the database.
    $con = mysqli_connect("localhost", $username, $pw, 'elliphinos');

    if (mysqli_connect_errno())
    {
      echo"Failed to connect to MySQL: ".mysqli_connect_error();
    }

    $phone2 = str_replace("-", "", $phone);
    $dob2 = str_replace("-", "", $dob);
    // Query for inserting all form data into the user table
    $query_result = mysqli_query($con,
      "insert into users(email, first_name, last_name, dob, address, phone, password)
                                            values('$email', '$first', '$last',
                                              '$dob', '$address', '$phone2',
                                              '$password')");

    								if (!($query_result)) {
    									echo '<span class="error">DATABASE FAILED TO ADD USER!</span>';
    								}

                                      //There should be another query for uploading the actual file for the abstract.
                                    mysqli_close($con);


                                      //Redirect to the home page after the form is successfully submitted.
                                    header("Location: signup_redirect.php");
                            }
                    }

                      //This function removes special characters from user input. Prevents script injection
                    function clean_field ($data)
                    {
                            $data = trim($data);
                            $data = stripslashes($data);
                            $data = htmlspecialchars($data);
                            return $data;
                    }

?>
                    

                <p><span class="error">* indica los campos obligatorios</span></p>
                <form method="post" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]);?>">
                        E-Mail: <input type="text" name="email" value="<?php echo $email?>">
                        <span class="error">* <?php echo $emailErr;?></span><br><br>
                       
                        Nombre: <input type="text" name="first" value="<?php echo $first?>">
                        <span class="error">* <?php echo $firstErr;?></span><br><br>
                       
					   Apellido: <input type="text" name="last" value="<?php echo $last?>">
                        <span class="error">* <?php echo $lastErr;?></span><br><br>
					   
                        Fecha de Nacimiento (a&ntildeo-mes-dia): <input type="text" name="dob" value="<?php echo $dob?>">
                        <span class="error">* <?php echo $dobErr;?></span><br><br>
                       
                        Numero telefonico: <input type="text" name="phone" value="<?php echo $phone?>">
                        <span class="error"> <?php echo $phoneErr;?></span><br><br>
                       
                        Direccion: <input type="text" name="address" value="<?php echo $address?>">
                        <span class="error"> <?php echo $addressErr;?></span><br><br>
						
                       Contrase&ntildea: <input type="password" name="password" value="<?php echo $password?>">
                        <span class="error">* <?php echo $passwordErr;?></span><br><br>
						
						Confirmar contrase&ntildea: <input type="password" name="confPassword" value="<?php echo $confPassword?>">
                        <span class="error">* <?php echo $passwordErr;?></span><br><br>
						
                        <input type="submit" name="submit" value="Registrate">
                    </div>
                </form>
				<a href="esp_login.html" id="back">Atras</a>
        </body>
</html>
